// product-manage.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    // 产品基本信息
    productForm: {
      name: '',
      specification: '',
      status: 1
    },
    statusIndex: 1,
    statusOptions: ['禁用', '启用'],
    
    // 型号信息列表
    modelList: [],
    
    // 当前编辑的型号
    currentModel: {
      name: '',
      model_code: '',
      fabric_color: '',
      description: ''
    },
    
    // 工序工价设置
    processes: [],
    processPrices: {},
    
    // 当前编辑的产品ID
    productId: null,
    // 当前编辑的型号ID
    modelId: null,
    
    // 页面状态
    currentStep: 'product', // product, models, price
    loading: false,
    
    // 工序列表
    processList: [],
    
    // 当前编辑的型号索引
    currentModelIndex: -1
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/product-manage/product-manage')) {
      return
    }
    
    this.loadProcesses()
  },

  // 加载工序列表
  async loadProcesses() {
    try {
      const res = await api.getProcesses()
      if (res.code === 1) {
        this.setData({
          processList: res.data || []
        })
        
        // 初始化工序工价
        const processPrices = {}
        res.data.forEach(process => {
          processPrices[process.id] = {
            piece_price: '',
            time_price: ''
          }
        })
        this.setData({ processPrices })
      }
    } catch (error) {
      console.error('加载工序列表失败:', error)
    }
  },

  // 产品名称输入
  onProductNameInput(e) {
    this.setData({
      'productForm.name': e.detail.value
    })
  },

  // 产品规格输入
  onProductSpecInput(e) {
    this.setData({
      'productForm.specification': e.detail.value
    })
  },

  // 产品状态选择
  onProductStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value),
      'productForm.status': parseInt(e.detail.value)
    })
  },

  // 型号名称输入
  onModelNameInput(e) {
    this.setData({
      'currentModel.name': e.detail.value
    })
  },

  // 型号编码输入
  onModelCodeInput(e) {
    this.setData({
      'currentModel.model_code': e.detail.value
    })
  },

  // 面料颜色输入
  onModelFabricColorInput(e) {
    this.setData({
      'currentModel.fabric_color': e.detail.value
    })
  },

  // 型号描述输入
  onModelDescInput(e) {
    this.setData({
      'currentModel.description': e.detail.value
    })
  },

  // 工序工价输入
  onProcessPriceInput(e) {
    const { processId, type } = e.currentTarget.dataset
    const value = e.detail.value
    
    this.setData({
      [`processPrices.${processId}.${type}`]: value
    })
  },

  // 下一步：创建产品
  async onNextStep() {
    if (this.data.currentStep === 'product') {
      if (!this.data.productForm.name.trim()) {
        wx.showToast({
          title: '请输入产品名称',
          icon: 'none'
        })
        return
      }
      
      this.setData({ loading: true })
      try {
        const res = await api.createProduct({
          name: this.data.productForm.name.trim(),
          description: this.data.productForm.specification.trim(),
          status: this.data.productForm.status
        })
        
        if (res.code === 1) {
          this.setData({
            productId: res.data.id,
            currentStep: 'models',
            loading: false
          })
          wx.showToast({
            title: '产品创建成功',
            icon: 'success'
          })
        } else {
          throw new Error(res.msg || '创建产品失败')
        }
      } catch (error) {
        console.error('创建产品失败:', error)
        wx.showToast({
          title: '创建产品失败',
          icon: 'none'
        })
        this.setData({ loading: false })
      }
    }
  },

  // 添加型号
  onAddModel() {
    if (!this.data.currentModel.name.trim()) {
      wx.showToast({
        title: '请输入型号名称',
        icon: 'none'
      })
      return
    }
    
    // 检查型号名称是否重复
    const existingModel = this.data.modelList.find(model => 
      model.name === this.data.currentModel.name.trim()
    )
    if (existingModel) {
      wx.showToast({
        title: '型号名称已存在',
        icon: 'none'
      })
      return
    }
    
    // 添加到型号列表
    const newModel = {
      ...this.data.currentModel,
      name: this.data.currentModel.name.trim(),
      model_code: this.data.currentModel.model_code.trim(),
      fabric_color: this.data.currentModel.fabric_color.trim(),
      description: this.data.currentModel.description.trim(),
      status: 1,
      id: Date.now() // 临时ID
    }
    
    this.setData({
      modelList: [...this.data.modelList, newModel],
      currentModel: {
        name: '',
        model_code: '',
        fabric_color: '',
        description: ''
      }
    })
    
    wx.showToast({
      title: '型号添加成功',
      icon: 'success'
    })
  },

  // 编辑型号
  onEditModel(e) {
    const { index } = e.currentTarget.dataset
    const model = this.data.modelList[index]
    
    this.setData({
      currentModel: { ...model },
      currentModelIndex: index
    })
  },

  // 删除型号
  onDeleteModel(e) {
    const { index } = e.currentTarget.dataset
    const model = this.data.modelList[index]
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除型号"${model.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          const newModelList = [...this.data.modelList]
          newModelList.splice(index, 1)
          this.setData({
            modelList: newModelList
          })
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 更新型号
  onUpdateModel() {
    if (!this.data.currentModel.name.trim()) {
      wx.showToast({
        title: '请输入型号名称',
        icon: 'none'
      })
      return
    }
    
    const newModelList = [...this.data.modelList]
    newModelList[this.data.currentModelIndex] = {
      ...this.data.currentModel,
      name: this.data.currentModel.name.trim(),
      model_code: this.data.currentModel.model_code.trim(),
      fabric_color: this.data.currentModel.fabric_color.trim(),
      description: this.data.currentModel.description.trim()
    }
    
    this.setData({
      modelList: newModelList,
      currentModel: {
        name: '',
        model_code: '',
        fabric_color: '',
        description: ''
      },
      currentModelIndex: -1
    })
    
    wx.showToast({
      title: '型号更新成功',
      icon: 'success'
    })
  },

  // 取消编辑型号
  onCancelEditModel() {
    this.setData({
      currentModel: {
        name: '',
        model_code: '',
        fabric_color: '',
        description: ''
      },
      currentModelIndex: -1
    })
  },

  // 选择型号设置工价
  onSelectModelForPrice(e) {
    const { index } = e.currentTarget.dataset
    const model = this.data.modelList[index]
    
    this.setData({
      currentModelIndex: index,
      currentStep: 'price'
    })
  },

  // 保存工序工价
  async onSavePrices() {
    if (this.data.currentModelIndex === -1) {
      wx.showToast({
        title: '请先选择型号',
        icon: 'none'
      })
      return
    }
    
    this.setData({ loading: true })
    
    try {
      const model = this.data.modelList[this.data.currentModelIndex]
      
      // 先创建型号
      const modelRes = await api.createProductModel({
        product_id: this.data.productId,
        name: model.name,
        model_code: model.model_code,
        fabric_color: model.fabric_color,
        description: model.description,
        status: model.status
      })
      
      if (modelRes.code !== 1) {
        throw new Error(modelRes.msg || '创建型号失败')
      }
      
      const modelId = modelRes.data.id
      
      // 保存工序工价
      const prices = []
      Object.keys(this.data.processPrices).forEach(processId => {
        const price = this.data.processPrices[processId]
        if (price.piece_price || price.time_price) {
          prices.push({
            model_id: modelId,
            process_id: parseInt(processId),
            price: parseFloat(price.piece_price) || 0,
            time_price: parseFloat(price.time_price) || 0,
            status: 1
          })
        }
      })
      
      if (prices.length === 0) {
        wx.showToast({
          title: '请至少设置一个工序工价',
          icon: 'none'
        })
        this.setData({ loading: false })
        return
      }
      
      // 批量保存工序工价
      for (const price of prices) {
        await api.createProcessPrice(price)
      }
      
      // 更新型号列表中的状态
      const newModelList = [...this.data.modelList]
      newModelList[this.data.currentModelIndex] = {
        ...newModelList[this.data.currentModelIndex],
        saved: true,
        modelId: modelId
      }
      
      this.setData({
        modelList: newModelList,
        loading: false
      })
      
      wx.showToast({
        title: '工序工价设置成功',
        icon: 'success'
      })
      
      // 重置工序工价
      const processPrices = {}
      this.data.processList.forEach(process => {
        processPrices[process.id] = {
          piece_price: '',
          time_price: ''
        }
      })
      this.setData({ processPrices })
      
    } catch (error) {
      console.error('保存工序工价失败:', error)
      wx.showToast({
        title: '保存工序工价失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  // 完成所有设置
  onFinish() {
    const unsavedModels = this.data.modelList.filter(model => !model.saved)
    if (unsavedModels.length > 0) {
      wx.showModal({
        title: '提示',
        content: `还有 ${unsavedModels.length} 个型号未设置工序工价，确定要完成吗？`,
        success: (res) => {
          if (res.confirm) {
            wx.showToast({
              title: '产品管理完成',
              icon: 'success'
            })
            setTimeout(() => {
              wx.navigateBack()
            }, 1500)
          }
        }
      })
    } else {
      wx.showToast({
        title: '产品管理完成',
        icon: 'success'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 上一步
  onPrevStep() {
    if (this.data.currentStep === 'models') {
      this.setData({ currentStep: 'product' })
    } else if (this.data.currentStep === 'price') {
      this.setData({ 
        currentStep: 'models',
        currentModelIndex: -1
      })
    }
  },

  // 取消
  onCancel() {
    wx.navigateBack()
  },

  // 检查权限
  hasPermission(module, action) {
    const app = getApp()
    const adminInfo = app.globalData.adminInfo
    if (!adminInfo || !adminInfo.id) {
      return false
    }
    return permissionUtils.hasPermission(adminInfo.id, module, action)
  }
})
